<?php

namespace app\api\model;

use app\admin\model\Config;
use app\admin\model\VipCard;
use app\api\controller\Vip;
use EasyWeChat\Factory;
use think\Exception;
use think\Model;


class MemberModel extends ApiModel
{

    // 表名
    protected $name = 'member';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $deleteTime = false;


    public function wxLogin($params)
    {
        try {
            if (empty($params['code'])) {
                throw new Exception('缺少参数');
            }
            $iv = $params['iv'] ?? '';
            $encryptedData = $params['encryptedData'] ?? '';
            $type = $params['type'] ?? 'own';
            $pid = $params['pid'] ?? 0;

            // 获取授权appid
            $app = Factory::miniProgram(config('wechat.xcx'));
            $data = $app->auth->session($params['code']);
            if (!$data) {
                throw new Exception('获取sessionKey和openId时异常');
            }

            $session = $data['session_key'];
            $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptedData);
            if (array_key_exists('phoneNumber', $decryptedData)) {
                $phone = $decryptedData['phoneNumber'];
            } else {
                throw new Exception('您没有授权手机号');
            }


            $userInfo = self::where(['phone' => $phone])->find();
            $time = time();
            if (!$userInfo) {
                $source = 0;
                //查询上级ID的ID
                $pidUser = (new MemberModel())->where(['id' =>$pid ])->find();
                //判断是否为分销进来的
                if ($type == 'advise') {
                    if($pidUser['source'] ==2){
                        $insert['ppid'] = $pidUser['pid'] ?? 0;
                    }
                    //财税顾问推广进来的
                    $insert['source'] = 2;
                    $source = 2;
                }

                if ($type == 'member') {
                    if($pidUser['source'] ==1){
                        $insert['ppid'] = $pidUser['pid'] ?? 0;
                    }
                    //团队分销进来的
                    $insert['source'] = 1;
                    $source = 1;
                }
                $insert['pid'] = $pid;

                //用户不存在，创建用户
                $last_four_digits = substr($phone, -4);
                $insert['nickname'] = $params['nickName'] ?? '栀芋堂_'.$last_four_digits;
                $insert['openid'] = $data['openid'];
                $insert['create_time'] = $time;
                $insert['phone'] = $phone ?? '';
                $userId = \think\Db::name('member')->insertGetId($insert);
                //生成推广二维码
                $path = 'pages/login/index?pid=' . $userId . "&type=member";
                $qrcode = (new Pay())->createQrcode($path, 'member', $userId);
                //添加二维码
                self::where(['id' => $userId])->update(['qrcode' => $qrcode]);

            } else {
                if ($userInfo['status'] == 0) {
                    throw new Exception('您的账号已被封禁');
                }
                $userId = $userInfo['id'];
                $source = $userInfo['source'];
            }
            $wxUserMes['user_token'] = (new Token())->product_token($userId, 1);
            //获取用户信息
            $wxUserMes['uid'] = $userId;
            $wxUserMes['source'] = $source;
            return $this->api_success('登陆成功', $wxUserMes);
        } catch (\Exception $e) {
            return $this->api_error($e->getMessage());
        }
    }

    public function userRetailInfo($params)
    {
        //获取用户信息
        $member = self::where(['id' => $params['uid']])->field('id,qrcode,team_total_money')->find();
        $member['qrcode'] = $this->createImg($member['qrcode']);

        //查询一级推荐多少人
        $first = self::where(['pid' => $member['id'], 'source' => 1])->select()->toArray();
        $member['first_retail_nums'] = count($first);
        $first_ids = array_column($first, 'id');
        //二级多少人
        $member['two_retail_nums'] = 0;
        if($first_ids){
            $member['two_retail_nums'] = self::where(['source' => 1])->whereIn('pid',$first_ids)->count();
        }


        return $this->api_success('获取成功', $member);
    }


    public function userRetailList($params)
    {
        //获取一级分销用户
        $retailList = self::where(['pid' => $params['uid'], 'source' => 1])->field('id,nickname,avatar,vip_type')->paginate(10);
        //查询会员信息
        $default_avatar = (new Config())->where(['id' => 26])->value('value');
        $vip = (new VipModel())->column('name', 'id');
        foreach ($retailList as &$val) {
            if(empty($val['avatar'])){
                $val['avatar'] = $this->createImg($default_avatar);
            }
            $val['vip_name'] = $vip[$val['vip_type']] ?? '';
            //查询总收入
            $val['income'] = (new MemberBill())->where(['retail_member_id' => $val['id'],'member_id' => $params['uid'], 'type'=>2])->sum('income');
        }

        return $this->api_success('获取成功', $retailList);
    }


    public function userRetailDetail($params)
    {
        $default_avatar = (new Config())->where(['id' => 26])->value('value');
        $retail_id = $params['retail_id'] ?? 0;
        $member = self::where(['id' => $retail_id])->find();
        $retailList = (new MemberBill())->where(['retail_member_id' => $retail_id, 'type'=>2])->field('id,income,create_time');
        $data['count'] = $retailList->count();
        $list = $retailList->order('id desc')->paginate(10);
        foreach ($list as &$val){
            $val['avatar'] = $member['avatar'] ?? $this->createImg($default_avatar);
            $val['nickname'] = $member['nickname'];
        }
        $data['list'] = $list;
        return $this->api_success('获取成功', $data);

    }


    public function getUser($params = array())
    {
        $uid = $params['uid'];
        $user = self::where(['id' => $uid])->find();
        if ($user['advise_qrcode']) {
            $user['advise_qrcode'] = $this->createImg($user['advise_qrcode']);
        }
        if ($user['qrcode']) {
            $user['qrcode'] = $this->createImg($user['qrcode']);
        }
        $user['vip_name'] = '开通会员 畅想会员权益';
        $user['discount'] = 0;
        if($user['vip_expire_time'] > time()){
            $vip = (new VipCard())->where(['id' => $user['vip_type']])->find();
            if ($vip) {
                $user['vip_name'] = "您是".$vip['name']."可享受".$vip['discount']."折扣";
                $user['discount'] =$vip['discount'];
            }
        }
        if(empty($user['avatar'])){
            $default_avatar = (new Config())->where(['id' => 26])->value('value');
            $user['avatar'] = $this->createImg($default_avatar);
        }

        if ($user['vip_expire_time'] > 0) {
            $user['vip_expire_time'] = date('Y.m.d', $user['vip_expire_time']) . "到期";
        }

        return $this->api_success('获取成功', $user);
    }

    public function createImg($img)
    {
        return config('app.image_url') . $img;
    }


    public function updateUser($params = array())
    {
        $nickname = $params['nickname'] ?? '';
        $avatar = $params['avatar'] ?? '';

        if(!$nickname || !$avatar){
            return $this->api_error('昵称或头像不能为空');
        }
        $user = self::where(['id' => $params['uid']])->find();
        if (!$user) {
            return ['code' => 201, 'msg' => '用户不存在'];
        }
        $user->nickname = $params['nickname'];
        $user->avatar = $params['avatar'];
        if ($user->save()) {
            return ['code' => 200, 'msg' => '保存成功', 'data' => $user->toArray()];
        }
        return ['code' => 201, 'msg' => '系统错误，请重新尝试！'];
    }


}
